﻿#include "AF_Application.h"
#include "AF_Timer.h"
#include "AF_Log.h"

namespace AF
{
	Application* Application::TheApp = NULL;
	Platform* Application::ThePlatform = NULL;

	void Application::DeleteAllMemory()
	{
		// 清除未释放的内存
		if(AF_MEM_SIZE() > 0)
		{
#ifdef AF_DEBUG
			_COUT << "The memory has " << AF_MEM_COUNT() << " handles not release." << _ENDL;
			_COUT << "Press any key to release all handles." << _ENDL;
#ifdef AF_DEBUG_MEMORY
			getchar();
#endif /*AF_DEBUG_MEMORY*/
#endif /*AF_DEBUG*/
			_COUT << "Cleaning memory..." << _ENDL;
			AF_MEM_RELEASE();
#ifdef AF_DEBUG
			_COUT << "All memory release finish." << _ENDL;
#endif /*AF_DEBUG*/
		}
	}

	Application::Application() :
		m_pMainWindow(NULL),
		m_pMainScene(NULL),
		m_isQuitApp(false)
	{
		if(TheApp == NULL)
			TheApp = this;
	}

	Application::~Application()
	{
		// 清除所有图片资源
		int nCount = Image::GetLinkCount();
		Image::DestroyAll();

		// 清除所有资源包
		Package::DestroyAll();

		if(TheApp == this)
			TheApp = NULL;
	}

	bool Application::InitApp()
	{
		if(TheApp == NULL)
		{
			TheApp = this;
		}
		else if(TheApp != this)
		{
			return false;
		}

		if(NULL == (ThePlatform = GetUsePlatform()))
		{
			return false;
		}

		CreateWindow cw;
		cw.pWindow		= NULL;
		cw.nWidth		= 800;
		cw.nHeight		= 600;
		cw.isFullScreen		= false;

		m_pMainScene = OnInitApp(cw);

		if(m_pMainScene == NULL)
		{
			return false;
		}

		m_pMainWindow = new AF_CWindow();
		if(m_pMainWindow->InitWindow(cw) == false)
		{
			return false;
		}

// 		m_pMainScene->SetWindow(m_pMainWindow);

		return true;
	}

	int Application::RunApp()
	{
		m_isQuitApp = false;
		if(m_pMainWindow != NULL)
		{
			if(m_pMainWindow->ShowWindow())
			{
				if(OnStartApp())
				{
					if(m_pMainScene != NULL)
						m_pMainWindow->RunWindow(m_pMainScene);
					OnFinishApp();
				}
			}
		}

		int nRtn = OnQuitApp();
		TheApp = NULL;
		return nRtn;
	}

	bool Application::QuitApp(bool isCommand)
	{
		bool isQuitApp = true;

		// 询问程序是否可以退出
		if(isQuitApp)
		{
			isQuitApp = OnExitApp(isCommand);
		}

		m_isQuitApp = isQuitApp;
		return m_isQuitApp;
	}

	void Application::UpdateApp()
	{
		// 更新
		OnUpdateApp();
	}

	Window* Application::GetWindow()
	{
		return m_pMainWindow;
	}

// 	void Application::SetWindow(Window* pWindow)
// 	{
// 		m_pMainWindow = pWindow;
// 	}
// 
// 	void Application::SetScene(Scene* pScene)
// 	{
// 		m_pMainScene = pScene;
// 	}

	void Application::UpdateTimers()
	{
		static bool s_isUpdate = false;

		if(!s_isUpdate)
		{
			s_isUpdate = true;
			Timer::UpdateTimers();
			s_isUpdate = false;
		}
	}

	void Application::UpdateExactTimers()
	{
		static bool s_isUpdate = false;

		if(!s_isUpdate)
		{
			s_isUpdate = true;
			Timer::UpdateExactTimers();
			s_isUpdate = false;
		}
	}
}

